package kr.co.casually.xml.parser;

import java.util.ArrayList;

import kr.co.casually.types.YouTubePlay;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class YouTubePlayXMLHandler extends DefaultHandler {
	YouTubePlay youTubePlay = null;
	public ArrayList<YouTubePlay> youTubePlays = null;

	private StringBuilder currentValue;
	public static String totalResult;

	public ArrayList<YouTubePlay> getList() {
		return youTubePlays;
	}

	public void setList(ArrayList<YouTubePlay> list) {
		youTubePlays = list;
	}
	
	
	public static String getTotalResult(){
		return totalResult;
	}

	/**
	 * Called when tag starts ( ex:- <name>AndroidPeople</name> -- <name> )
	 */
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		currentValue = new StringBuilder();

		if (qName.equalsIgnoreCase("feed")) {
			if (youTubePlays != null) {
				youTubePlays.clear();
			} else {
				youTubePlays = new ArrayList<YouTubePlay>();
			}

			youTubePlay = new YouTubePlay();

		} else if (qName.equalsIgnoreCase("entry")) {
			youTubePlay = new YouTubePlay();

			// media content url

		} else if (qName.equalsIgnoreCase("media:player")) {

			youTubePlay.setContentUrl(attributes.getValue("url"));
			// thumnail
		} else if (qName.equalsIgnoreCase("media:thumbnail")) {
			if (attributes.getValue("yt:name").equals("hqdefault")) {
				youTubePlay.setThumbnail(attributes.getValue("url"));
			}
			// duration
		} else if (qName.equalsIgnoreCase("yt:duration")) {
			youTubePlay.setDuration(attributes.getValue("seconds"));
			// view count
		} else if (qName.equalsIgnoreCase("yt:statistics")) {
			youTubePlay.setViewCount(attributes.getValue("viewCount"));

		}
	}

	/**
	 * Called when tag closing ( ex:- <name>AndroidPeople</name> -- </name> )
	 */
	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		/** set value */
		if (qName.equalsIgnoreCase("title")) {
			youTubePlay.setTitle(currentValue.toString().trim());
		} else if (qName.equalsIgnoreCase("name")) {
			youTubePlay.setAuthName(currentValue.toString().trim());
		} else if (qName.equalsIgnoreCase("yt:uploaded")) {
			youTubePlay.setUploaded(currentValue.toString().trim());
		} else if (qName.equalsIgnoreCase("openSearch:totalResults")) {
			totalResult=currentValue.toString().trim();
		} else if (qName.equalsIgnoreCase("entry")) {
			youTubePlays.add(youTubePlay);
		}
	}

	/**
	 * Called to get tag characters ( ex:- <name>AndroidPeople</name> -- to get
	 * AndroidPeople Character )
	 */
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		// currentValue = new String(ch, start, length);

		currentValue.append(ch, start, length);

	}

}
